import os
from selenium import webdriver
from selenium.webdriver.chrome.service import Service


class GetDriver:
    driver = None
    filename = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

    @classmethod
    def get_driver(cls, url):
        # 单例驱动实例是否存在
        if cls.driver is None:
            # 构建Chrome驱动程序的路径
            service = Service(
                os.path.join(cls.filename, "config", "chromedriver.exe")
            )
            # 初始化Chrome浏览器驱动
            cls.driver = webdriver.Chrome(service=service)
            # 访问指定URL
            cls.driver.get(url)
        # 返回已创建的驱动实例
        return cls.driver

    @classmethod
    def quit_driver(cls):
        # 判断驱动实例是否存在
        if cls.driver is not None:
            cls.driver.quit()
            # 重置驱动实例为None
            cls.driver = None